package com.etocrm.saas.lib.base.resource.config;

import com.etocrm.saas.lib.base.resource.Util.UrlMatchaerUtil;
import com.etocrm.saas.lib.base.resource.exception.AuthExceptionEntryPoint;
import com.etocrm.saas.lib.base.resource.exception.CustomAccessDeniedHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;


@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    //公钥
    private static final String PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqX3CNKSiLi2zRz0t3L+6Mj1ifE+Ozk7ATmzy4zwPe2U3UCvi5yH+D9jnkkMuY7TdRiYnbbu7BkarG+JR3bis+9bJ1WS4WyDTUFgRXk9JFEpCOvg9c34ZPWvK0Ei5WvGKys+6udL8TYH8ObR48sTdPOAZILmI8ahl6mdhvUM/f/PIKg1W3hYEkC5Uh7DNN2OPnHm05+Fsg08S+nbtRBetfMw46VZA7/ahfSrpikA/dqxRjn1e511jn0gVAQRH0a+8UPhCDjtXmJt5wksKTsL3hTv+rv5qSUsEvPiYfdbbXXTkW36KEPbI4pXx9FUSfRMzmFVG/WC69i/cWxvFp5xluwIDAQAB-----END PUBLIC KEY-----";

    //定义JwtTokenStore，使用jwt令牌方式
    @Bean
    public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
        return new JwtTokenStore(jwtAccessTokenConverter);
    }

    //定义JJwtAccessTokenConverter，使用jwt令牌
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setVerifierKey(getPubKey());
        return converter;
    }
    
    /**
     * 获取非对称加密公钥 Key
     */
    private String getPubKey() {
/*        Resource resource = new ClassPathResource(PUBLIC_KEY);
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
            BufferedReader br = new BufferedReader(inputStreamReader);
            return br.lines().collect(Collectors.joining("\n"));
        } catch (IOException ioe) {
            return null;
        }*/
        return PUBLIC_KEY;
    }
    
    //Http安全配置
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers(UrlMatchaerUtil.urlMatchartUrls).permitAll() //放行路径配置
                .anyRequest().anonymous();//忽略
                //.anyRequest().authenticated();//拦截
    }

    @Bean
    public AuthenticationEntryPoint authExceptionEntryPoint(){
        return new AuthExceptionEntryPoint();
    }

    @Bean
    public AccessDeniedHandler accessDeniedHandler(){
        return new CustomAccessDeniedHandler();
    }

    //资源服务安全配置,配置自定义异常
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                .authenticationEntryPoint(authExceptionEntryPoint())
                .accessDeniedHandler(accessDeniedHandler());
    }


}


